package com.example.work7

import android.annotation.SuppressLint
import android.app.*
import android.content.Context
import android.content.Intent
import android.media.MediaPlayer
import android.os.Binder
import android.os.Build
import android.os.IBinder
import android.provider.MediaStore
import android.util.Log
import java.io.IOException

class MusicService : Service() {
    companion object {
        val Commond = "Operate"
    }

    val TAG = "MusicService"
    val Channel_ID = "my channel"
    val Notification_ID = 1
    val mediaPlayer = MediaPlayer()
    val musicList = mutableListOf<String>()
    val musicNameList = mutableListOf<String>()
    var current = 0
    var isPause = false
    val binder = MusicBinder()

    // 音乐绑定器
    inner class MusicBinder : Binder() {
        val musicName: String
            get() = if (musicNameList.isNotEmpty()) musicNameList[current] else "No Music"
        var currentPosition: Int
            get() = mediaPlayer.currentPosition
            set(value) = mediaPlayer.seekTo(value)
        val duration: Int
            get() = mediaPlayer.duration
        val size: Int
            get() = musicList.size
        val currentIndex: Int
            get() = current
    }

    // 服务创建时的处理
    @SuppressLint("ForegroundServiceType")
    override fun onCreate() {
        super.onCreate()
        getMusicList()
        val builder: Notification.Builder
        val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(Channel_ID, "test", NotificationManager.IMPORTANCE_MIN)
            notificationManager.createNotificationChannel(channel)
            builder = Notification.Builder(this, Channel_ID)
        } else {
            builder = Notification.Builder(this)
        }
        val intent = Intent(this, MainActivity::class.java)
        val pendingIntent = PendingIntent.getActivity(this, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)
        val notification = builder.setSmallIcon(R.drawable.ic_notification)
            .setContentTitle("音乐")
            .setContentText("this is a music")
            .setContentIntent(pendingIntent)
            .build()
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
            // 只有在 Android 10 及以下版本时才需要调用 startForeground
            startForeground(1, notification)
        } else {
            // 在 Android 11 及以上版本，使用 startForegroundService 启动服务
            val serviceIntent = Intent(this, MusicService::class.java)
            startForegroundService(serviceIntent)

            // 请求 FOREGROUND_SERVICE 权限
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                try {
                    startForeground(1, notification)
                } catch (e: SecurityException) {
                    e.printStackTrace()
                }
            }
        }
        startForeground(1, notification)

        mediaPlayer.setOnPreparedListener {
            it.start()
            val notification2 = builder.setSmallIcon(R.drawable.ic_notification)
                .setContentTitle("音乐")
                .setContentText(musicNameList.get(current))
                .setContentIntent(pendingIntent)
                .build()
            notificationManager.notify(1, notification2)
            val intent2 = Intent(MyReceiverAction)
            intent2.putExtra("operate", 1)
            intent2.setPackage(packageName)
            sendBroadcast(intent2)
        }
    }

    // 服务启动时的处理
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        val operate = intent?.getIntExtra(Commond, 1) ?: 1
        when (operate) {
            1 -> play()
            2 -> pause()
            3 -> stop()
            4 -> next()
            5 -> prev()
        }

        return super.onStartCommand(intent, flags, startId)
    }

    // 暂停音乐
    fun pause() {
        if (isPause) {
            mediaPlayer.start()
            isPause = false
        } else {
            mediaPlayer.pause()
            isPause = true
        }
    }

    // 停止音乐
    fun stop() {
        mediaPlayer.stop()
        stopSelf()
    }

    // 播放下一首音乐
    fun next() {
        current++
        if (current >= musicList.size) {
            current = 0
        }
        play()
    }

    // 播放上一首音乐
    fun prev() {
        current--
        if (current < 0) {
            current = musicList.size - 1
        }
        play()
    }

    // 播放音乐
    fun play() {
        if (musicList.size == 0) return
        val path = musicList[current]
        mediaPlayer.reset()
        try {
            mediaPlayer.setDataSource(path)
            mediaPlayer.prepareAsync()
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }

    // 绑定服务时的处理
    override fun onBind(intent: Intent): IBinder {
        return binder
    }

    // 获取音乐列表
    @SuppressLint("Range")
    private fun getMusicList() {
        val cursor = contentResolver.query(
            MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
            null,
            null,
            null,
            null
        )
        if (cursor != null) {
            while (cursor.moveToNext()) {
                val musicPath = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA))
                musicList.add(musicPath)
                val musicName =
                    cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE))
                musicNameList.add(musicName)
                Log.d(TAG, "getMusicList: $musicPath name:$musicName")
            }
            cursor.close()
        }
    }
}